package com.example.musicplayer

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : ComponentActivity(), ServiceConnection {
    companion object {
        private const val REQUEST_CODE = 100 // 选择一个合适的请求码
    }

    val Channel_ID = "my channel"
    val Notification_ID = 1
    var binder: MusicService.MusicBinder? = null
    val TAG = "MainActivity"

    private lateinit var textView1: TextView
    private lateinit var textView2: TextView
    private lateinit var seekBar1: SeekBar
    private lateinit var button1: Button

    @SuppressLint("NotificationPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestPermissions()  // 请求权限
        textView1 = findViewById(R.id.textView1)
        textView2 = findViewById(R.id.textView2)
        seekBar1 = findViewById(R.id.seekBar1)

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 0)
        } else {
             startMusicService()
        }

        seekBar1.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    binder?.currentPosition = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }
    private fun requestPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_CODE)
        }
    }

    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }
    fun onPlay(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 1)
        startService(intent)
        updateNotification() // 更新通知
    }

    fun onPause(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 2)
        startService(intent)
    }

    fun onStop(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 3)
        startService(intent)
    }

    fun onNext(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 4)
        startService(intent)
        updateNotification() // 更新通知
    }

    fun onPrev(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Command, 5)
        startService(intent)
        updateNotification() // 更新通知
    }

    // 添加一个更新通知的方法
    @SuppressLint("NotificationPermission")
    private fun updateNotification() {
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: Notification.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(Channel_ID, "channel1", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(notificationChannel)
            builder = Notification.Builder(this, Channel_ID)
        } else {
            builder = Notification.Builder(this)
        }

        // 获取当前音乐名称
        val musicName = binder?.musicName ?: "正在播放音乐"

        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_IMMUTABLE)
        } else {
            PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        }

        val notification = builder.setSmallIcon(R.drawable.ic_stat_name)  // 确保图标存在
            .setContentTitle("音乐播放器")
            .setContentText(musicName)  // 设置为当前播放的音乐名称
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        notificationManager.notify(Notification_ID, notification)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "Permission granted, loading music")
            startMusicService()  // 权限授予后获取音乐
        } else {
            Log.d(TAG, "Permission denied, cannot load music")
        }
    }



    override fun onDestroy() {
        super.onDestroy()
        unbindService(this)
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        binder = service as MusicService.MusicBinder

        val handler = Handler(Looper.getMainLooper())
        val runnable = object : Runnable {
            @SuppressLint("SetTextI18n")
            override fun run() {
                binder?.let {
                    seekBar1.max = it.duration
                    seekBar1.progress = it.currentPosition
                    textView1.text = it.musicName
                    textView2.text = "${it.currentIndex + 1}/${it.size}"
                }
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(runnable)
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }
}
